package com.starter.home.controller;


import com.starter.home.domain.entity.User;
import com.starter.home.service.IUserService;
import com.starter.home.util.CommonParam;
import com.starter.home.util.PageUtil;
import com.starter.home.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author
 * @since 2020-04-29
 */
@RestController
@RequestMapping("/user")
@ControllerAdvice
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 用户登录 存储 session 去除pwd返回前端
     * @param user
     * @param session
     * @return
     */
    @PostMapping(value = "/login")
    public ResponseResult login(@RequestBody User user, HttpSession session){
        User user1 = userService.toLogin(user);
        session.setAttribute("user",user1);
        user1.setPwd("");
        return ResponseResult.success(user1);
    }


    /**
     * 更改状态
     * @return
     */
    @PostMapping(value = "/changeStatus/{id}/{status}")
    public ResponseResult changeStatus(@PathVariable Integer id,@PathVariable Boolean status){
        userService.changeStatus(id,status);
        return ResponseResult.success(null);
    }
    /**
     * 删除用户
     * @return
     */
    @PostMapping(value = "/delete/{id}")
    public ResponseResult delete(@PathVariable Integer id){
        userService.deleteById(id);
        return ResponseResult.success(null);
    }


    /**
     * 查找用户
     * @return
     */
    @GetMapping(value = "/getList")
    public ResponseResult getList(@ModelAttribute CommonParam commonParam){
        PageUtil pageUtil = userService.getUserList(commonParam);
        return ResponseResult.success(pageUtil);
    }

    @PostMapping(value = "/register")
    public ResponseResult register(@RequestBody User user){
        user.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        boolean save = userService.save(user);
        if (save){
            return ResponseResult.success(null);
        }else{
            return ResponseResult.error(null);
        }
    }

}
